import Vue from 'vue'
import Router from 'vue-router'
import cookie from 'cookiejs'
import jwt from 'jsonwebtoken'
// import HelloWorld from '@/components/HelloWorld'
// const _import_ = file => () => import('views/' + file + '.vue')
const _import_ = file => () => import('@/views/' + file)
// const login = resolve => require(['@/views/login'], resolve)

Vue.use(Router)

var routes = [
  {
    path: '/',
    meta: {
      title: '首页'
    },
    component: _import_('index')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录'
    },
    component: _import_('login')
  },
  {
    path: '/chat',
    name: 'chat',
    meta: {
      title: 'chatRoom'
    },
    component: _import_('chat')
  },
  {
    path: '/list',
    name: 'list',
    meta: {
      title: '动态'
    },
    component: _import_('list')
  },
  {
    path: '/avatar',
    name: 'avatar',
    meta: {
      title: '修改头像'
    },
    component: _import_('avatar')
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    name: '404',
    component: _import_('404')
  }
]
const router = new Router({routes})
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  jwt.verify(cookie('zp_token'), 'token', (err, res) => {
    if (!err) {
      if (to.name === 'login') router.push('')
    } else {
      cookie.remove('zp_token')
      if (to.name !== 'login') router.push('login')
    }
  })
  // if (!(cookie('zp_token') && (jwt.verify(cookie('zp_token'), 'token').account))) {
  //   if (to.name !== 'login') router.push('login')
  // } else {
  //   if (to.name === 'login') router.go(0)
  // }
  next()
})
router.afterEach((to, from) => {
  jwt.verify(cookie('zp_token'), 'token', (err, res) => {
    if (!err) {
      if (to.name === 'login') router.push('')
    } else {
      cookie.remove('zp_token')
      if (to.name !== 'login') router.push('login')
    }
  })
})
export default router
